package com.ruoyi.combat.repository;

import com.ruoyi.combat.domain.neo4j.CombatAtlasTask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CombatAtlasTaskRepository extends Neo4jRepository<CombatAtlasTask, Long> {

    /**
     * 分页查询任务节点信息
     */
    @Query(value = "MATCH (n:AtlasTask) " +
            "WHERE ($targetIp IS NULL OR n.targetIp = $targetIp) " +
            "AND ($taskStatus IS NULL OR n.taskStatus = $taskStatus) " +
            "AND ($type IS NULL OR n.type = $type) " +
            "RETURN n " +
            "ORDER BY n.startTime DESC " +
            "SKIP $pageNum * $pageSize LIMIT $pageSize",
            countQuery = "MATCH (n:AtlasTask) " +
                    "WHERE ($targetIp IS NULL OR n.targetIp = $targetIp) " +
                    "AND ($taskStatus IS NULL OR n.taskStatus = $taskStatus) " +
                    "AND ($type IS NULL OR n.type = $type) " +
                    "RETURN count(n)")
    Page<CombatAtlasTask> findByAtlasTaskPage(
            @Param("targetIp") String targetIp,
            @Param("taskStatus") String taskStatus,
            @Param("type") String type,
            @Param("pageNum") Integer pageNum,
            @Param("pageSize") Integer pageSize,
            Pageable pageable);

    /**
     * 修改任务状态和结束时间和抗归属后组织信息
     */
    @Query("MATCH (n:AtlasTask) WHERE n._id = $id " +
            "SET " +
            "n.taskStatus = CASE WHEN $taskStatus IS NOT NULL THEN $taskStatus ELSE n.taskStatus END, " +
            "n.endTime = CASE WHEN $endTime IS NOT NULL THEN $endTime ELSE n.endTime END, " +
            "n.afterRiskOrg = CASE WHEN $afterRiskOrg IS NOT NULL THEN $afterRiskOrg ELSE n.afterRiskOrg END " +
            "RETURN n ")
    void updateCombatAtlasTaskById(@Param("id") Long id,
                                   @Param("taskStatus") String taskStatus,
                                   @Param("endTime") String endTime,
                                   @Param("afterRiskOrg") String afterRiskOrg);

    /**
     * 删除任务节点信息
     */
    @Query("MATCH (n:AtlasTask) WHERE n._id = $id DELETE n")
    void deleteCombatAtlasTaskById(@Param("id") Long id);

    /**
     * 根据类型，查询所有未完成的任务节点信息
     */
    @Query("MATCH (n:AtlasTask) WHERE n.taskStatus = '1' AND n.type = $type RETURN n")
    List<CombatAtlasTask> findByAtlasTaskPage(@Param("type") String type);

    /**
     * 查询所有已完成的任务节点信息
     */
    @Query("MATCH (n:AtlasTask) WHERE n.taskStatus = '2' RETURN count(n)")
    long findFinishedByAtlasTask();


}
